var App = angular.module('App', ["ui.router", 'oc.lazyLoad', 'App.controllers', 'App.directives', 'App.services', 'App.filters', 'App.router'])

    .factory('HttpInterceptor', function ($rootScope) {
        // ---
        // PRVIATE METHODS.
        // ---
        // I serialize the given Object into a key-value pair string. This
        // method expects an object and will default to the toString() method.
        // --
        // NOTE: This is an atered version of the jQuery.param() method which
        // will serialize a data collection for Form posting.
        // --
        // https://github.com/jquery/jquery/blob/master/src/serialize.js#L45
        function serializeData(data) {
            // If this is not an object, defer to native stringification.
            if (!angular.isObject(data)) {
                return ((data == null) ? "" : data.toString());
            }
            var buffer = [];
            // Serialize each key in the object.
            for (var name in data) {
                if (!data.hasOwnProperty(name)) {
                    continue;
                }
                var value = data[name];
                if (angular.isObject(value)) {
                    value = angular.toJson(value);
                }
                buffer.push(encodeURIComponent(name) + "=" + encodeURIComponent((value == null) ? "" : value));
            }
            // Serialize the buffer and clean it up for transportation.
            var source = buffer.join("&").replace(/%20/g, "+");
            return (source);
        }

        return {
            request: function (config) {
            	config.data = config.data || {};
                if (config.data && angular.isObject(config.data)) {
                    if (config.method === 'POST') {
                    	config.data.access_token = $rootScope.user ? $rootScope.user.access_token : '';
                        config.data = serializeData(config.data);
                    } else if (config.method === 'GET') {
                        config.url += (config.url.indexOf('?') > 0 ? '&' : '?') + serializeData(config.data);
                    }
                }
                return config;
            }
        };
    })

    .factory('AuthInterceptor', ["$q", "$rootScope", function ($q, $rootScope) {
        return {
            request: function (config) {
                if ($rootScope.user) {
                    config.headers["userId"] = $rootScope.user.id;
                }
                return config;
            },
            responseError: function (response) {
                if (response.status == 871202 || (response.status == 401 && response.statusText == 'Unauthorized')) {// 如果是登录超时
                    $rootScope.$emit("userLoginIntercepted", response);
                }
                return $q.reject(response);
            }
        };
    }])

    .run(["$rootScope", "$state", '$window', 'sessionStore', function ($rootScope, $state, $window, sessionStore) {
        $rootScope.$state = $state; // state to be accessed from view
        
        $rootScope.user = sessionStore.getObject('user');
        
        $rootScope.$on('$stateChangeStart', function (event, toState, toParams, fromState, fromParams) {
            if (toState.name == 'login') {
                $rootScope.user = null;
                $window.sessionStorage.clear();// 删除sessionStorage
            } else if (toState.auth && (!$rootScope.user || !$rootScope.user.access_token)) {
    			event.preventDefault();// 取消默认跳转行为
    			toState.params = toParams;
    			toParams.toState = toState;
    			$state.go("login", {'toState' : toState});
    		} 
        });

        // 刷新时，如果不是登录页面，则获取用户信息
        if ($window.location.href.indexOf('#') > 0 && $window.location.href.indexOf('#/login') < 0 && $window.sessionStorage['user']) {
            $rootScope.user = angular.fromJson($window.sessionStorage["user"]);
        }
    }])

;


var AppUtil = function() {
    return {
        getModelName: function(modelName) {
            if (modelName.indexOf(".") > 0) {
                modelName = modelName.substring(modelName.lastIndexOf(".") + 1, modelName.length);
            }
            return modelName;
        },
        getModelValue: function(scope, modelName) {
            if (modelName.indexOf(".") > 0) {
                var arr = modelName.split(".");
                var value = scope;
                $(arr).each(function(ii, modelName2) {
                    if (angular.isUndefined(value)) {
                        value = null;
                        return false;
                    } else {
                        value = value[modelName2];
                    }
                });
                return value;
            } else {
                return scope[modelName];
            }
        },
        setModelValue: function(scope, modelName, modeValue) {
            if (modelName.indexOf(".") > 0) {
                var arr = modelName.split(".");
                var value = scope;
                $(arr).each(function(ii, modelName2) {
                    if (ii == arr.length - 1) {
                        value[modelName2] = modeValue;
                    } else {
                        if (angular.isUndefined(value[modelName2])) {
                            value[modelName2] = {};
                        }
                        value = value[modelName2];
                    }
                });
            } else {
                scope[modelName] = modeValue;
            }
        },
        jsonfy: function(json) {
            return eval("[{" + (json || "") + "}]")[0];
        }
    };
}();
